package com.example.rbac.service.impl;

import com.example.rbac.entity.Page;
import com.example.rbac.entity.defefult.DateDefult;
import com.example.rbac.mapper.CurdMapper;
import com.example.rbac.mapper.cache.RedisDao;
import com.example.rbac.service.CurdService;
import com.example.rbac.uitls.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/10/19.
 */
public class CurdServiceImpl<Repository extends CurdMapper<Entity>, Entity extends DateDefult> implements CurdService<Entity>{

    @Autowired
    protected Repository repository;

    @Autowired
    protected RedisDao<Entity> redisDao;

    protected Class<Entity> clz;

    public CurdServiceImpl() {
        clz = (Class<Entity>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public Entity get(String id) {
        Entity t = redisDao.getObject(id, clz);
        if (t == null){
            return repository.get(id);
        }
        return t;
    }

    @Override
    public List<Entity> findList() {
        return repository.findList();
    }

    @Override
    public Integer save(Entity t) {
        if (!StringUtils.isNotEmpty(t.getId())){
            String id = UUID.randomUUID().toString().replace("-", "");
            t.setId(id);
        }
        return repository.save(t);
    }

    @Override
    public Integer update(Entity t) {
        return repository.update(t);
    }

    @Override
    public Page<Entity> getPager(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null){
            Page page = new Page();
            pageNum = page.getCurrentPageNum();
            pageSize = page.getPerPageSize();
        }
        List<Entity> list = repository.getPager((pageNum- 1) * pageSize, pageSize);
        Page<Entity> page = new Page<>(pageNum, pageSize, list, getCount());
        return page;
    }

    @Override
    public int getCount() {
        return repository.getCount();
    }
}
